package com.example.research.controller;

import com.example.research.dto.ApiResponse;
import com.example.research.entity.User;
import com.example.research.service.AuthService;
import com.example.research.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/users")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("未提供有效的认证信息");
        }
        String token = authHeader.substring(7);
        return authService.getUserIdFromToken(token);
    }

    /**
     * 查询所有用户
     */
    @GetMapping
    public ApiResponse<List<User>> getAllUsers() {
        try {
            List<User> users = userService.findAll();
            return ApiResponse.success(users);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户的详细信息
     */
    @GetMapping("/profile")
    public ApiResponse<User> getCurrentUserProfile(@RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            User user = userService.findById(currentUserId);

            if (user == null) {
                return ApiResponse.notFound("用户不存在");
            }

            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新当前用户的详细信息
     */
    @PutMapping("/profile")
    public ApiResponse<User> updateCurrentUserProfile(@Valid @RequestBody User userInfo,
                                                     @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);

            // 只能更新自己的信息
            userInfo.setId(currentUserId);
            User updated = userService.updateUser(userInfo);
            return ApiResponse.success("个人信息更新成功", updated);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 修改当前用户密码
     */
    @PostMapping("/change-password")
    public ApiResponse<String> changeCurrentUserPassword(@RequestBody Map<String, String> passwordData,
                                                        @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);

            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return ApiResponse.badRequest("旧密码和新密码不能为空");
            }

            userService.changePassword(currentUserId, oldPassword, newPassword);
            return ApiResponse.success("密码修改成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询用户
     */
    @GetMapping("/{id}")
    public ApiResponse<User> getUserById(@PathVariable Long id) {
        try {
            User user = userService.findById(id);
            if (user == null) {
                return ApiResponse.notFound("用户不存在");
            }
            return ApiResponse.success(user);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据角色查询用户
     */
    @GetMapping("/role/{roleName}")
    public ApiResponse<List<User>> getUsersByRole(@PathVariable String roleName) {
        try {
            List<User> users = userService.findByRole(roleName);
            return ApiResponse.success(users);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 创建用户
     */
    @PostMapping
    public ApiResponse<User> createUser(@Valid @RequestBody User user,
                                      @RequestParam(required = false, defaultValue = "STUDENT") String roleName) {
        try {
            User createdUser = userService.createUser(user, roleName);
            return ApiResponse.success("用户创建成功", createdUser);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public ApiResponse<User> updateUser(@PathVariable Long id,
                                      @Valid @RequestBody User user,
                                      @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            User currentUser = userService.findById(currentUserId);

            // 检查权限：只有管理员或用户本人可以修改用户信息
            if (!currentUser.isAdmin() && !currentUserId.equals(id)) {
                return ApiResponse.forbidden("没有权限修改其他用户信息");
            }

            user.setId(id);
            User updatedUser = userService.updateUser(user);
            return ApiResponse.success("用户信息更新成功", updatedUser);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteUser(@PathVariable Long id,
                                        @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            User currentUser = userService.findById(currentUserId);

            // 检查权限：只有管理员可以删除用户
            if (!currentUser.isAdmin()) {
                return ApiResponse.forbidden("没有权限删除用户");
            }

            userService.deleteUser(id);
            return ApiResponse.success("用户删除成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/{id}/change-password")
    public ApiResponse<String> changePassword(@PathVariable Long id,
                                            @RequestBody Map<String, String> passwordData,
                                            @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            User currentUser = userService.findById(currentUserId);

            // 检查权限：只有管理员或用户本人可以修改密码
            if (!currentUser.isAdmin() && !currentUserId.equals(id)) {
                return ApiResponse.forbidden("没有权限修改其他用户密码");
            }

            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return ApiResponse.badRequest("旧密码和新密码不能为空");
            }

            userService.changePassword(id, oldPassword, newPassword);
            return ApiResponse.success("密码修改成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/{id}/assign-role")
    public ApiResponse<String> assignRole(@PathVariable Long id,
                                        @RequestParam String roleName,
                                        @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            User currentUser = userService.findById(currentUserId);

            // 检查权限：只有管理员可以分配角色
            if (!currentUser.isAdmin()) {
                return ApiResponse.forbidden("没有权限分配角色");
            }

            userService.assignRole(id, roleName);
            return ApiResponse.success("角色分配成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 移除用户角色
     */
    @PostMapping("/{id}/remove-role")
    public ApiResponse<String> removeRole(@PathVariable Long id,
                                        @RequestParam String roleName,
                                        @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            User currentUser = userService.findById(currentUserId);

            // 检查权限：只有管理员可以移除角色
            if (!currentUser.isAdmin()) {
                return ApiResponse.forbidden("没有权限移除角色");
            }

            userService.removeRole(id, roleName);
            return ApiResponse.success("角色移除成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 启用/禁用用户
     */
    @PostMapping("/{id}/toggle-status")
    public ApiResponse<String> toggleUserStatus(@PathVariable Long id,
                                              @RequestHeader("Authorization") String authHeader) {
        try {
            Long currentUserId = getCurrentUserId(authHeader);
            User currentUser = userService.findById(currentUserId);

            // 检查权限：只有管理员可以启用/禁用用户
            if (!currentUser.isAdmin()) {
                return ApiResponse.forbidden("没有权限修改用户状态");
            }

            userService.toggleUserStatus(id);
            return ApiResponse.success("用户状态修改成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

}
